package com.autodatabase.xml;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class XMLUtil {
	public void write() {
		Document document = getDocument();
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("GBK");
		XMLWriter writer;

		try {
			writeXML(document);
			writer = new XMLWriter(new FileWriter(file), format);
			writer.write(document);
			writer.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void read() {
		Document document = getDocument();
		parseXML(document);
	}

	private Document getDocument() {
		getFile();
		Document document = null;

		if(!file.exists()) {
			document = DocumentHelper.createDocument();
		}
		else {
			try {
				SAXReader reader = new SAXReader();
				document = reader.read(file);
			} 
			catch (DocumentException e) {
				e.printStackTrace();
			}
		}

		return document;
	}

	protected void writeXML(Document document) {
		//to be overrided.
	}

	protected void parseXML(Document document) {
		//to be overrided.
	}

	public void getFile() {
		if(file == null) {
			file = new File(getFilePath());
		}
	}

	public boolean renameTemplate(String newPath) {
		getFile();
		boolean isSuc = file.renameTo(new File(newPath));
		this.filePath = isSuc ? newPath : filePath;

		return isSuc;
	}

	public boolean deleteTemplate(String tpath) {
		File file = new File(tpath);
		
		if(file.exists()) {
			return file.delete();
		}
		
		return false;
	}

	public String getFilePath() {
		return filePath;
	}

	public String getFileSampleName() {
		return file.getName().substring(0, file.getName().indexOf("."));
	}

	private String filePath;
	public File file;
}
